<template>
  <a-spin :spinning="confirmLoading" class="spin-style">
    <j-form-container style="width: 100%;">
      <a-form-model ref="form" :model="model" slot="detail">
        <a-row :gutter="24">
          <a-col :span="14">
            <a-row>
              <a-col :span="24">
                <div class="data-item-info" v-if="roadDetailVisible">
                  <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="道路名称">{{ model.roadName }}</a-descriptions-item>
                    <a-descriptions-item label="道路编号">{{ model.code }}</a-descriptions-item>
                    <a-descriptions-item label="道路标签">{{ model.roadTag_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="所属示范区">{{ model.zoneId_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="道路属性">{{ model.roadAttr_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="道路类型">{{ model.roadType_dictText }}</a-descriptions-item>
                  </a-descriptions>
                </div>

                <div class="data-item-info" v-if="crossDetailVisible">
                  <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="路口名称">{{ crossModel.name }}</a-descriptions-item>
                    <a-descriptions-item label="路口编号">{{ crossModel.code }}</a-descriptions-item>
                    <a-descriptions-item label="所属示范区">{{ crossModel.zoneId_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="所属道路">{{ crossModel.roadName }}</a-descriptions-item>
                    <a-descriptions-item label="路口形态">{{ crossModel.crossForm_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="路口标签">{{ crossModel.crossTag_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="路口级别">{{ crossModel.level_dictText }}</a-descriptions-item>
                  </a-descriptions>
                </div>

                <div class="data-item-info" v-if="poleDetailVisible">
                  <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="路侧杆件">{{ poleModel.crossName + '-' + poleModel.positionType_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="所属道路">{{ poleModel.roadName }}</a-descriptions-item>
                    <a-descriptions-item label="所属路口">{{ poleModel.crossName }}</a-descriptions-item>
                    <a-descriptions-item label=""></a-descriptions-item>
                    <a-descriptions-item label="经纬度" :span="2">
                      {{ poleModel.lng }}, {{ poleModel.lat }}
                    </a-descriptions-item>
                  </a-descriptions>
                </div>

                <div class="data-item-info" v-if="deviceDetailVisible">
                  <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="设备编号">{{ deviceModel.deviceId }}</a-descriptions-item>
                    <a-descriptions-item label="序列号">{{ deviceModel.serialNumber }}</a-descriptions-item>
                    <a-descriptions-item label="设备类型">{{ deviceModel.deviceType_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="厂商">{{ deviceModel.manufacturerId_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="路侧杆件">{{ deviceModel.crossName + '-' + deviceModel.polePositionType_dictText }}</a-descriptions-item>
                    <a-descriptions-item label="所属道路">{{ deviceModel.roadName }}</a-descriptions-item>
                    <a-descriptions-item label="所属路口">{{ deviceModel.crossName }}</a-descriptions-item>
                    <a-descriptions-item label="状态" :span="2">
                      <a-tag :color="deviceModel.onlineState === 1 ? 'green' : 'red'">
                        {{ deviceModel.onlineState_dictText }}
                      </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="经纬度" :span="2">
                      {{ deviceModel.lng }}, {{ deviceModel.lat }}
                    </a-descriptions-item>
                  </a-descriptions>
                </div>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <div class="children-list">
                  <a-tabs :activeKey="activeKey" type="card" @change="handleTabChange">
                    <a-tab-pane key="1" tab="关联路口">
                      <a-table
                        ref="table"
                        size="middle"
                        :scroll="{x:true}"
                        bordered
                        rowKey="id"
                        :columns="crossColumns"
                        :dataSource="dataSource"
                        :pagination="ipagination"
                        :loading="loading"
                        class="j-table-force-nowrap"
                        @change="handleCrossTableChange"
                        >
                        <span slot="action" slot-scope="text, record">
                          <a @click="viewCrossDetail(record)">详情</a>
                        </span>
                      </a-table>
                    </a-tab-pane>
                    <a-tab-pane key="2" tab="关联路侧杆件">
                      <a-table
                        ref="table"
                        size="middle"
                        :scroll="{x:true}"
                        bordered
                        rowKey="id"
                        :columns="poleColumns"
                        :dataSource="dataSource"
                        :pagination="ipagination"
                        :loading="loading"
                        class="j-table-force-nowrap"
                        @change="handlePoleTableChange"
                        >
                        <span slot="action" slot-scope="text, record">
                          <a @click="viewPoleDetail(record)">详情</a>
                        </span>
                      </a-table>
                    </a-tab-pane>
                    <a-tab-pane key="3" tab="关联设备">
                      <a-table
                        ref="table"
                        size="middle"
                        :scroll="{x:true}"
                        bordered
                        rowKey="id"
                        :columns="deviceColumns"
                        :dataSource="dataSource"
                        :pagination="ipagination"
                        :loading="loading"
                        class="j-table-force-nowrap"
                        @change="handleDeviceTableChange"
                        >
                        <span slot="action" slot-scope="text, record">
                          <a @click="viewDeviceDetail(record)">详情</a>
                        </span>
                      </a-table>
                    </a-tab-pane>
                  </a-tabs>
                </div>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="10">
            <a-row>
              <div style="width: 600px; height: 750px">
                <!-- <div id="map_canvas" style="width: 500px; height: 500px"></div> -->
                <BMap :pageHeight="550" ref="map" :zoom="12"></BMap>
              </div>
            </a-row>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { filterObj } from '@/utils/util';
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import BMap from '@/views/components/map/index.vue'
  import { gws84 } from '@/views/components/map/js/BD09-WGS84'
import { add } from 'xe-utils/methods';

  export default {
    name: 'TRoadDetailForm',
    components: {
      JDictSelectTag,
      BMap
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
        },
        crossModel: {
        },
        poleModel: {
        },
        deviceModel: {
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        activeKey: '1',
        confirmLoading: false,
        url: {
          crosslist: "/basicinfo/roadSurface/crossing/list",
          polelist: "/basicinfo/roadside/pole/list",
          devicelist: "/basicinfo/roadsideDevice/all/listByCondition",
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {
        },
        /* 数据源 */
        dataSource:[],
        /* 分页参数 */
        ipagination:{ 
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter:{
          column: 'createTime',
          order: 'desc',
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading:false,
        // 路口表头
        crossColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'路口编号',
            align:"center",
            dataIndex: 'code'
          },
          {
            title:'路口名称',
            align:"center",
            dataIndex: 'name'
          },
          {
            title:'关联杆件数',
            align:"center",
            dataIndex: 'poleNum'
          },
          {
            title:'设备数量',
            align:"center",
            dataIndex: 'deviceNum'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 杆件表头
        poleColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'路侧杆件ID',
            align:"center",
            dataIndex: 'facilityId'
          },
          {
            title:'路口名称',
            align:"center",
            dataIndex: 'crossName'
          },
          {
            title:'路侧杆件位置',
            align:"center",
            dataIndex: 'positionType_dictText'
          },
          {
            title:'设备数量',
            align:"center",
            dataIndex: 'deviceNum'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 设备表头
        deviceColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'设备编号',
            align:"center",
            dataIndex: 'deviceId'
          },
          {
            title:'路口名称',
            align:"center",
            dataIndex: 'crossName'
          },
          {
            title:'设备厂商',
            align:"center",
            dataIndex: 'manufacturerId_dictText'
          },
          {
            title:'设备类型',
            align:"center",
            dataIndex: 'dtype_dictText'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        markerImageWidth: 32,
        markerImageHeight: 32,
        crossMarker: null,
        poleMarker: null,
        deviceMarker: null,
        poleListType: 'road',
        deviceListType: 'road',
        roadDetailVisible: true,
        crossDetailVisible: false,  
        poleDetailVisible: false,
        deviceDetailVisible: false,
        markers: [],
        markerIconMap:{
          cross: 'assets/icons/map/cross-red.png',
          pole: 'assets/icons/map/pole-red.png',
          device: 'assets/operationalSupervision/map/point-icon5.png'
        },
        deviceMarkerIconMap:{
          camera: 'assets/operationalSupervision/map/point-icon3.png',
          rsu: 'assets/operationalSupervision/map/point-icon1.png',
          radar: 'assets/operationalSupervision/map/point-icon2.png',
          signallamp: 'assets/operationalSupervision/map/point-icon6.png',
          mec: 'assets/operationalSupervision/map/point-icon4.png',
        },
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      
    },
    mounted() {
      
    },
    methods: {
      view (record) {
        this.model = Object.assign({}, record);
        console.log("view model", this.model)
        // this.detailVisible = true;
        this.addPolylines(record);
        this.queryCrossListByObjId(this.model.id, true);
      },
      // 添加道路标记
      addPolylines(dataItem) {
        console.log('添加道路标记:', dataItem)
        if (!dataItem.wkt) {
          console.warn('道路缺少经纬度信息:', dataItem)
          return
        }
        let points = [];
        try {
          let wkt = dataItem.wkt;
          const xyArr = wkt.split(',');
          for (let i = 0; i < xyArr.length; i++) {
            const xy = xyArr[i].split(' ');
            const lng = parseFloat(xy[0]);
            const lat = parseFloat(xy[1]);
            // 坐标转换（如果需要）
            let coordinates = {
              lng: parseFloat(lng),
              lat: parseFloat(lat)
            }
            
            // 如果是WGS84坐标，需要转换为百度坐标
            if (dataItem.coordinateType === 'WGS84') {
              const gcj02Point = gws84().wgs84togcj02(coordinates.lng, coordinates.lat)
              coordinates = gws84().gcj02tobd09(gcj02Point.lng, gcj02Point.lat)
            }
            
            const point = new BMapGL.Point(coordinates.lng, coordinates.lat);
            points.push(point);
          }
        
          // 创建标记点
          let polyline = new BMapGL.Polyline(points, {
            strokeColor: "blue",
            strokeWeight: 2
          });
          this.$refs.map.polyline = polyline;
          this.$refs.map.map.addOverlay(polyline);      
          this.$refs.map.setViewportToPolyline(polyline);
        } catch (error) {
          console.error('添加道路标记失败:', error, dataItem)
        }
      },
      queryCrossListByObjId(objId, isInit){
        if(isInit){
          this.ipagination.current = 1;
        }
        console.log("objId", objId);
        this.queryParam = {};
        this.queryParam.roadId = objId;
        this.loadData(this.url.crosslist, "cross");
      },
      queryPoleListByObjId(objId, isInit){
        if(isInit){
          this.ipagination.current = 1;
        }
        console.log("objId: ", objId, "type: ", this.poleListType);
        this.queryParam = {};
        if(this.poleListType === 'cross'){
          this.queryParam.crossId = objId;
        }else{
          this.queryParam.roadId = objId;
        }
        this.loadData(this.url.polelist, "pole");
      },
      queryDeviceListByObjId(objId, isInit){
        if(isInit){
          this.ipagination.current = 1;
        }
        console.log("objId: ", objId, "type: ", this.deviceListType);
        this.queryParam = {};
        if(this.deviceListType === 'pole'){
          this.queryParam.poleId = objId;
        }else{
          this.queryParam.roadId = objId;
        }
        this.loadData(this.url.devicelist, "device");
      },
      //tab切换事件
      handleTabChange(key){
        console.log("key", key);
        this.activeKey = key;
        this.poleListType = 'road';
        this.deviceListType = 'road';
        this.dataSource = [];
        if(key === '1'){
          this.queryCrossListByObjId(this.model.id, true);
        }else if(key === '2'){
          this.queryPoleListByObjId(this.model.id, true);
        }else if(key === '3'){
          this.queryDeviceListByObjId(this.model.id, true);
        }
      },
      loadData(url, type) {
        const that = this;
        //加载数据 若传入参数1则加载第一页的内容
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(url, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records||res.result;
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
            that.addListMarkers(that.dataSource, type);
          }else{
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      addListMarkers(dataSource, type){
        const that = this;
        that.$refs.map.removeMarkers(that.markers); // 清除之前的标记点
        that.markers = [];
        let iconPath = that.markerIconMap[type];
        console.log("addListMarkers", dataSource, type, iconPath);
        console.log("dataSource", dataSource, dataSource.length);
        if(dataSource && dataSource.length > 0){
          dataSource.forEach(item => {
            console.log("item", item);
            let lnglat = {"lng": item.lng, "lat": item.lat};
            //根据类型设置图片
            if(type === 'device' && item.dtype){
              iconPath = that.deviceMarkerIconMap[item.dtype] || that.markerIconMap['device'];
            }
            console.log("addListMarker", item, type, iconPath);
            let marker = that.$refs.map.addImageMarker(lnglat, {iconPath: iconPath, width: that.markerImageWidth, height: that.markerImageHeight});
            that.markers.push(marker);
          }); 

        }
      },
      getQueryParams() {
        //获取查询条件
        let sqp = {}
        if(this.superQueryParams){
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
        // param.field = this.getQueryField();
        param.field = null;
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      handleCrossTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.queryCrossListByObjId(this.model.id, false);
      },
      handlePoleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.queryPoleListByObjId(this.model.id, false);
      },
      handleDeviceTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.queryDeviceListByObjId(this.model.id, false);
      },
      viewCrossDetail(detail){
        console.log("detail", detail);
        this.activeKey='2';
        const that = this;
        this.crossModel = Object.assign({}, detail);
        this.showCrossDetail();
        this.poleListType = "cross";
        this.queryPoleListByObjId(detail.id, true);
        // this.$refs.map.clearOverlays();
        this.$refs.map.removeOverlay(this.crossMarker)
        const lnglat = {"lng": detail.lng, "lat": detail.lat};
        // this.$refs.map.addImageMarker(lnglat, {iconPath: 'assets/icons/map/cross-red.png', width: that.markerImageWidth, height: that.markerImageHeight});
        this.$refs.map.setCenterAndZoom(lnglat, this.$refs.map.zoom);
      },
      viewPoleDetail(detail){
        console.log("detail", detail);
        this.activeKey='3'
        const that = this;
        this.poleModel = Object.assign({}, detail);
        this.showPoleDetail();
        this.deviceListType = 'pole';
        this.queryDeviceListByObjId(detail.id, true);
        // this.$refs.map.clearOverlays();
        this.$refs.map.removeOverlay(this.poleMarker)
        const lnglat = {"lng": detail.lng, "lat": detail.lat};
        // this.$refs.map.addImageMarker(lnglat, {iconPath: 'assets/icons/map/pole-red.png', width: that.markerImageWidth, height: that.markerImageHeight});
        this.$refs.map.setCenterAndZoom(lnglat, this.$refs.map.zoom);
      },
      viewDeviceDetail(detail){
        console.log("detail", detail);
        const that = this;
        this.deviceModel = Object.assign({}, detail);
        this.showDeviceDetail();
        // this.$refs.map.clearOverlays();
        // this.$refs.map.removeOverlay(this.deviceMarker)
        const lnglat = {"lng": detail.lng, "lat": detail.lat};
        // const dtype = detail.dtype;
        //根据类型设置图片
        // let iconPath = 'assets/icons/map/dot-red.png';
        // if(dtype){
        //   iconPath = that.deviceMarkerIconMap[dtype] || that.markerIconMap['device'];
        // }
        // this.deviceMarker = this.$refs.map.addImageMarker(lnglat, {iconPath: iconPath, width: that.markerImageWidth, height: that.markerImageHeight});
        this.$refs.map.setCenterAndZoom(lnglat, this.$refs.map.zoom);
      },
      showCrossDetail(){
        this.roadDetailVisible = false;
        this.crossDetailVisible = true;
        this.poleDetailVisible = false;
        this.deviceDetailVisible = false;
      },
      showPoleDetail(){
        this.roadDetailVisible = false;
        this.crossDetailVisible = false;
        this.poleDetailVisible = true;
        this.deviceDetailVisible = false;
      },
      showDeviceDetail(){
        this.roadDetailVisible = false;
        this.crossDetailVisible = false;
        this.poleDetailVisible = false;
        this.deviceDetailVisible = true;
      },
    }
  }
</script>
<style  scoped>
  div.ant-modal, div.ant-modal-content {
      width: 1480px;
  }
  .spin-style{
      width: 1280px;
  }
  .tip-label-style{
    display: inline;
    width: 100%;
    text-align: center;
    font-size: 10px;
    color: red;
  }
  .area-select.medium{
    width: 100px;
  }
  .data-item-info {
    .ant-descriptions {
      margin-top: 0px;
    }
  }
  .children-list{
    margin-top: 15px;
  }
</style>